﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Xml.Serialization;
using System.Xml;

namespace MapEditor
{
    public class TileLayer : IXmlSerializable
    {
        int[,] map;

        public int Width
        {
            get { return map.GetLength(1); }
        }

        public int Height
        {
            get { return map.GetLength(0); }
        }

        public int this[int x, int y]
        {
            set { if (x < Height && y < Width && x >= 0 && y >= 0) map[x, y] = value; }
            get { if (x < Height && y < Width && x >= 0 && y >= 0) return map[x, y]; return -2; }
        }

        public TileLayer()
        {
            this.map = null;
        }

        public TileLayer(int[,] m)
        {
            this.map = m;
        }

        public System.Xml.Schema.XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(System.Xml.XmlReader reader)
        {
            List<List<string>> data = new List<List<string>>();
            List<string> row;
            int deth = reader.Depth;

            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    if (reader.Name == "row")
                    {
                        if (reader.Read())
                        {
                            if (reader.NodeType == XmlNodeType.Text)
                            {
                                row = new List<string>();
                                string[] cells = reader.Value.Split(",".ToCharArray());
                                foreach (string s in cells)
                                    row.Add(s);
                                data.Add(row);
                            }
                        }
                    }
                }
                if (deth == reader.Depth)
                    break;
            }
            map = new int[data.Count, data[0].Count];
            for (int i = 0; i < Height; i++)
                for (int j = 0; j < Width; j++)
                    map[i, j] = int.Parse(data[i][j]);
        }

        public void WriteXml(System.Xml.XmlWriter writer)
        {
            for (int i = 0; i < Height; i++)
            {
                StringBuilder row = new StringBuilder(Width * Height * 3);
                for (int j = 0; j < Width; j++)
                {
                    row.Append(map[i, j].ToString());
                    if (j != Width - 1)
                        row.Append(", ");
                }
                writer.WriteElementString("row", row.ToString());
            }
        }
    }
}
